import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;

// 图书类，用于存储图书信息
class Book {
    List<ImageIcon> homeImages;
    String name;
    double price;

    public Book(List<ImageIcon> homeImages, String name, double price) {
        this.homeImages = homeImages;
        this.name = name;
        this.price = price;
    }
}

// 消息类，用于存储消息信息
class Message {
    String sender;
    String content;
    String time;

    public Message(String sender, String content, String time) {
        this.sender = sender;
        this.content = content;
        this.time = time;
    }

    @Override
    public String toString() {
        return sender + ": " + content + " (" + time + ")";
    }
}

// 聊天记录类，用于存储与某个用户的聊天记录
class ChatHistory {
    List<Message> messages = new ArrayList<>();

    public void addMessage(Message message) {
        messages.add(message);
    }

    public Message getLastMessage() {
        if (messages.isEmpty()) {
            return null;
        }
        return messages.get(messages.size() - 1);
    }
}

// 购物车项类，包含图书和勾选状态
class CartItem {
    Book book;
    JCheckBox checkBox;

    public CartItem(Book book) {
        this.book = book;
        this.checkBox = new JCheckBox();
    }
}

public class SecondHandBookApp extends JFrame {
    private JPanel contentPanel;
    private JPanel homePanel;
    private List<Book> allBooks = new ArrayList<>();
    private List<Book> displayedBooks = new ArrayList<>();
    private JPanel bookListPanel;
    private JTextField searchField;
    private Map<String, ChatHistory> chatHistories = new HashMap<>();
    private JPanel messageListPanel;
    private List<CartItem> cart = new ArrayList<>();
    private JPanel cartPanel;
    private JLabel totalPriceLabel;

    public SecondHandBookApp() {
        // 设置全局字体为支持中文的字体
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            Font font = new Font("宋体", Font.PLAIN, 12);
            UIManager.put("Label.font", font);
            UIManager.put("Button.font", font);
            UIManager.put("TextField.font", font);
            UIManager.put("TextArea.font", font);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 设置窗口标题
        setTitle("简易二手图书交易软件");
        // 设置窗口大小
        setSize(800, 600);
        // 设置关闭操作
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 设置窗口布局
        setLayout(new BorderLayout());

        // 创建内容面板
        contentPanel = new JPanel();
        contentPanel.setLayout(new CardLayout());

        // 创建各个界面
        homePanel = createHomePanel();
        JPanel messagePanel = createMessagePanel();
        cartPanel = createCartPanel();
        JPanel profilePanel = createProfilePanel();

        // 将各个界面添加到内容面板
        contentPanel.add(homePanel, "home");
        contentPanel.add(messagePanel, "message");
        contentPanel.add(cartPanel, "cart");
        contentPanel.add(profilePanel, "profile");

        // 创建导航栏面板
        JPanel navPanel = createNavPanel();

        // 添加内容面板和导航栏到主窗口
        add(contentPanel, BorderLayout.CENTER);
        add(navPanel, BorderLayout.SOUTH);

        // 初始显示首页
        showPanel("home");
    }

    // 创建首页面板
    private JPanel createHomePanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 创建搜索框
        searchField = new JTextField();
        searchField.setPreferredSize(new Dimension(200, 30));
        searchField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                filterBooks(searchField.getText());
            }
        });
        JPanel searchPanel = new JPanel();
        searchPanel.add(searchField);
        panel.add(searchPanel, BorderLayout.NORTH);

        // 创建图书列表面板
        bookListPanel = new JPanel(new GridLayout(0, 5, 10, 10));
        JScrollPane scrollPane = new JScrollPane(bookListPanel);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 初始化图书数据
        generateRandomBooks(20);
        displayedBooks.addAll(allBooks);
        updateBookList();

        // 监听滚动事件，实现无限滚动
        scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
            @Override
            public void adjustmentValueChanged(AdjustmentEvent e) {
                JScrollBar scrollBar = (JScrollBar) e.getSource();
                if (scrollBar.getValue() + scrollBar.getVisibleAmount() >= scrollBar.getMaximum() - 10) {
                    int oldSize = allBooks.size();
                    generateRandomBooks(10);
                    List<Book> newBooks = allBooks.subList(oldSize, allBooks.size());
                    String keyword = searchField.getText().toLowerCase();
                    for (Book book : newBooks) {
                        if (keyword.isEmpty() || book.name.toLowerCase().contains(keyword)) {
                            displayedBooks.add(book);
                        }
                    }
                    updateBookList();
                }
            }
        });

        return panel;
    }

    // 生成随机图书
    private void generateRandomBooks(int count) {
        Random random = new Random();
        String[] bookNames = {"Java编程思想", "Effective Java", "代码整洁之道", "重构", "设计模式", "算法导论"};
        List<ImageIcon> homeImages = new ArrayList<>();
        for (int i = 1; i <= 3; i++) {
            ImageIcon image = loadAndResizeImage("/" + i + ".png", 100, 150);
            if (image != null) {
                homeImages.add(image);
            } else {
                System.err.println("图片加载失败，请检查路径。");
            }
        }
        if (!homeImages.isEmpty()) {
            for (int i = 0; i < count; i++) {
                String name = bookNames[random.nextInt(bookNames.length)];
                double price = random.nextDouble() * 100 + 10;
                allBooks.add(new Book(homeImages, name, price));
            }
        }
    }

    // 加载并缩放图片
    private ImageIcon loadAndResizeImage(String path, int width, int height) {
        try {
            java.net.URL imageUrl = getClass().getResource(path);
            if (imageUrl == null) {
                System.err.println("图片资源未找到，尝试的路径: " + path);
                System.err.println("类路径根目录: " + getClass().getResource("/"));
                return null;
            }
            System.out.println("成功找到图片资源，路径: " + imageUrl.getPath());
            BufferedImage originalImage = ImageIO.read(imageUrl);
            Image scaledImage = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            return new ImageIcon(scaledImage);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 过滤图书
    private void filterBooks(String keyword) {
        displayedBooks.clear();
        for (Book book : allBooks) {
            if (book.name.toLowerCase().contains(keyword.toLowerCase())) {
                displayedBooks.add(book);
            }
        }
        updateBookList();
    }

    // 更新图书列表
    private void updateBookList() {
        Random random = new Random();
        bookListPanel.removeAll();
        for (Book book : displayedBooks) {
            JPanel bookPanel = new JPanel(new BorderLayout());
            JLabel imageLabel = new JLabel(book.homeImages.get(random.nextInt(book.homeImages.size())));
            JLabel nameLabel = new JLabel(book.name);
            JLabel priceLabel = new JLabel(String.format("¥%.2f", book.price));
            bookPanel.add(imageLabel, BorderLayout.CENTER);
            bookPanel.add(nameLabel, BorderLayout.NORTH);
            bookPanel.add(priceLabel, BorderLayout.SOUTH);
            bookPanel.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    showBookDetail(book);
                }
            });
            bookListPanel.add(bookPanel);
        }
        bookListPanel.revalidate();
        bookListPanel.repaint();
    }

    // 创建导航栏面板
    private JPanel createNavPanel() {
        JPanel navPanel = new JPanel(new GridLayout(1, 4, 0, 0));
        navPanel.setBackground(Color.LIGHT_GRAY);

        JButton homeButton = createNavButton("首页", "home");
        JButton messageButton = createNavButton("消息", "message");
        JButton cartButton = createNavButton("购物车", "cart");
        JButton profileButton = createNavButton("我的", "profile");

        navPanel.add(homeButton);
        navPanel.add(messageButton);
        navPanel.add(cartButton);
        navPanel.add(profileButton);

        return navPanel;
    }

    // 创建导航按钮
    private JButton createNavButton(String text, String panelName) {
        JButton button = new JButton(text);
        button.setBorderPainted(false);
        button.setFocusPainted(false);
        button.setContentAreaFilled(false);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showPanel(panelName);
            }
        });
        return button;
    }

    // 创建消息面板
    private JPanel createMessagePanel() {
        JPanel panel = new JPanel(new BorderLayout());

        messageListPanel = new JPanel();
        messageListPanel.setLayout(new BoxLayout(messageListPanel, BoxLayout.Y_AXIS));

        generateRandomMessages(10);

        JScrollPane scrollPane = new JScrollPane(messageListPanel);
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    // 生成随机消息
    private void generateRandomMessages(int count) {
        Random random = new Random();
        String[] senders = {"张三", "李四", "王五", "赵六"};
        String[] contents = {"这本书多少钱？", "有货吗？", "能便宜点吗？", "什么时候发货？"};
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

        for (int i = 0; i < count; i++) {
            String sender = senders[random.nextInt(senders.length)];
            String content = contents[random.nextInt(contents.length)];
            String time = sdf.format(new Date());
            Message message = new Message(sender, content, time);

            chatHistories.computeIfAbsent(sender, k -> new ChatHistory()).addMessage(message);

            addMessageListItem(sender);
        }
    }

    // 添加消息列表项
    private void addMessageListItem(String sender) {
        ChatHistory chatHistory = chatHistories.get(sender);
        Message lastMessage = chatHistory.getLastMessage();

        JPanel itemPanel = new JPanel(new BorderLayout());
        itemPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY));
        itemPanel.setPreferredSize(new Dimension(messageListPanel.getWidth(), 60));

        JLabel senderLabel = new JLabel(sender);
        // 单独设置人名标签字体
        senderLabel.setFont(new Font("宋体", Font.BOLD, 16));
        JLabel contentLabel = new JLabel(lastMessage.content);
        JLabel timeLabel = new JLabel(lastMessage.time);

        JPanel infoPanel = new JPanel(new BorderLayout());
        infoPanel.add(senderLabel, BorderLayout.NORTH);
        infoPanel.add(contentLabel, BorderLayout.CENTER);

        itemPanel.add(infoPanel, BorderLayout.WEST);
        itemPanel.add(timeLabel, BorderLayout.EAST);

        itemPanel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                showChatPanel(sender);
            }
        });

        messageListPanel.add(itemPanel);
        messageListPanel.revalidate();
        messageListPanel.repaint();
    }

    // 显示聊天面板
    private void showChatPanel(String sender) {
        JDialog chatDialog = new JDialog(this, "与 " + sender + " 聊天", true);
        chatDialog.setSize(400, 400);
        chatDialog.setLayout(new BorderLayout());

        JTextArea chatArea = new JTextArea();
        chatArea.setEditable(false);
        JScrollPane chatScrollPane = new JScrollPane(chatArea);
        chatDialog.add(chatScrollPane, BorderLayout.CENTER);

        // 显示历史聊天记录
        ChatHistory chatHistory = chatHistories.computeIfAbsent(sender, k -> new ChatHistory());
        for (Message message : chatHistory.messages) {
            if (message.sender.equals(sender)) {
                chatArea.append(sender + " (" + message.time + "): " + message.content + "\n");
            } else {
                chatArea.append("我 (" + message.time + "): " + message.content + "\n");
            }
        }
        chatArea.setCaretPosition(chatArea.getDocument().getLength());

        JPanel inputPanel = new JPanel(new BorderLayout());
        JTextField inputField = new JTextField();
        JButton sendButton = new JButton("发送");

        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage(chatArea, inputField, sender);
            }
        });

        inputField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    sendMessage(chatArea, inputField, sender);
                }
            }
        });

        inputPanel.add(inputField, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);
        chatDialog.add(inputPanel, BorderLayout.SOUTH);

        chatDialog.setVisible(true);
    }

    // 发送消息并自动回复
    private void sendMessage(JTextArea chatArea, JTextField inputField, String sender) {
        String message = inputField.getText().trim();
        if (!message.isEmpty()) {
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            String time = sdf.format(new Date());
            Message myMessage = new Message("我", message, time);
            chatHistories.get(sender).addMessage(myMessage);
            chatArea.append("我 (" + time + "): " + message + "\n");

            // 自动回复
            Random random = new Random();
            String[] replies = {"好的", "稍后回复", "价格可商量", "有货"};
            String reply = replies[random.nextInt(replies.length)];
            String replyTime = sdf.format(new Date());
            Message replyMessage = new Message(sender, reply, replyTime);
            chatHistories.get(sender).addMessage(replyMessage);
            chatArea.append(sender + " (" + replyTime + "): " + reply + "\n");

            inputField.setText("");
            chatArea.setCaretPosition(chatArea.getDocument().getLength());

            // 更新消息列表项
            updateMessageListItem(sender);
        }
    }

    // 更新消息列表项
    private void updateMessageListItem(String sender) {
        for (Component component : messageListPanel.getComponents()) {
            if (component instanceof JPanel) {
                JPanel itemPanel = (JPanel) component;
                JLabel senderLabel = (JLabel) ((JPanel) itemPanel.getComponent(0)).getComponent(0);
                if (senderLabel.getText().equals(sender)) {
                    ChatHistory chatHistory = chatHistories.get(sender);
                    Message lastMessage = chatHistory.getLastMessage();

                    JLabel contentLabel = (JLabel) ((JPanel) itemPanel.getComponent(0)).getComponent(1);
                    JLabel timeLabel = (JLabel) itemPanel.getComponent(1);

                    contentLabel.setText(lastMessage.content);
                    timeLabel.setText(lastMessage.time);

                    messageListPanel.revalidate();
                    messageListPanel.repaint();
                    break;
                }
            }
        }
    }

    // 创建购物车面板
    private JPanel createCartPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        JPanel cartItemsPanel = new JPanel();
        cartItemsPanel.setLayout(new BoxLayout(cartItemsPanel, BoxLayout.Y_AXIS));
        JScrollPane scrollPane = new JScrollPane(cartItemsPanel);
        panel.add(scrollPane, BorderLayout.CENTER);

        JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        totalPriceLabel = new JLabel("总价: ¥0.00");
        JButton checkoutButton = new JButton("结算");
        // 增大结算按钮尺寸
        checkoutButton.setPreferredSize(new Dimension(120, 40));
        checkoutButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                double total = 0;
                Iterator<CartItem> iterator = cart.iterator();
                while (iterator.hasNext()) {
                    CartItem item = iterator.next();
                    if (item.checkBox.isSelected()) {
                        total += item.book.price;
                        iterator.remove();
                    }
                }
                JOptionPane.showMessageDialog(SecondHandBookApp.this, "结算总价: ¥" + total);
                updateCartPanel();
            }
        });
        bottomPanel.add(totalPriceLabel);
        bottomPanel.add(checkoutButton);
        panel.add(bottomPanel, BorderLayout.SOUTH);

        return panel;
    }

    // 更新购物车面板
    private void updateCartPanel() {
        JPanel cartItemsPanel = (JPanel) ((JScrollPane) cartPanel.getComponent(0)).getViewport().getView();
        cartItemsPanel.removeAll();

        for (CartItem item : cart) {
            JPanel itemPanel = new JPanel(new BorderLayout());
            itemPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY));
            itemPanel.setPreferredSize(new Dimension(cartItemsPanel.getWidth(), 80));

            JLabel imageLabel = new JLabel(item.book.homeImages.get(0));
            JPanel infoPanel = new JPanel();
            infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
            JLabel nameLabel = new JLabel(item.book.name);
            nameLabel.setFont(new Font("宋体", Font.BOLD, 14));
            JLabel priceLabel = new JLabel(String.format("¥%.2f", item.book.price));
            priceLabel.setFont(new Font("宋体", Font.PLAIN, 12));
            infoPanel.add(nameLabel);
            infoPanel.add(priceLabel);

            JPanel leftPanel = new JPanel(new BorderLayout());
            leftPanel.add(imageLabel, BorderLayout.WEST);
            leftPanel.add(infoPanel, BorderLayout.CENTER);

            itemPanel.add(leftPanel, BorderLayout.WEST);
            itemPanel.add(item.checkBox, BorderLayout.EAST);

            item.checkBox.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    updateTotalPrice();
                }
            });

            itemPanel.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    showBookDetail(item.book);
                }
            });

            cartItemsPanel.add(itemPanel);
            cartItemsPanel.add(Box.createVerticalStrut(5));
        }

        updateTotalPrice();
        cartItemsPanel.revalidate();
        cartItemsPanel.repaint();
    }

    // 更新总价显示
    private void updateTotalPrice() {
        double total = 0;
        for (CartItem item : cart) {
            if (item.checkBox.isSelected()) {
                total += item.book.price;
            }
        }
        totalPriceLabel.setText("总价: ¥" + String.format("%.2f", total));
    }

    // 创建我的面板
    private JPanel createProfilePanel() {
        JPanel panel = new JPanel();
        panel.add(new JLabel("我的 - 个人信息"));
        return panel;
    }

    // 显示指定的面板
    private void showPanel(String panelName) {
        CardLayout cardLayout = (CardLayout) contentPanel.getLayout();
        cardLayout.show(contentPanel, panelName);
        if ("cart".equals(panelName)) {
            updateCartPanel();
        }
    }

    // 显示图书详情页
    private void showBookDetail(Book book) {
        JDialog detailDialog = new JDialog(this, book.name, true);
        detailDialog.setSize(800, 800);
        detailDialog.setLayout(new BorderLayout());

        // 重新加载详情页所需尺寸的图片
        List<ImageIcon> detailImages = new ArrayList<>();
        for (int i = 1; i <= 3; i++) {
            ImageIcon image = loadAndResizeImage("/" + i + ".png", 500, 600);
            if (image != null) {
                detailImages.add(image);
            } else {
                System.err.println("图片加载失败，请检查路径。");
            }
        }

        // 商品轮播图
        JPanel imagePanel = new JPanel(new BorderLayout());
        JLabel imageLabel = new JLabel(detailImages.get(0));
        int[] currentIndex = {0};

        JButton prevButton = new JButton("<");
        prevButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                currentIndex[0] = (currentIndex[0] - 1 + detailImages.size()) % detailImages.size();
                imageLabel.setIcon(detailImages.get(currentIndex[0]));
            }
        });

        JButton nextButton = new JButton(">");
        nextButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                currentIndex[0] = (currentIndex[0] + 1) % detailImages.size();
                imageLabel.setIcon(detailImages.get(currentIndex[0]));
            }
        });

        imagePanel.add(prevButton, BorderLayout.WEST);
        imagePanel.add(imageLabel, BorderLayout.CENTER);
        imagePanel.add(nextButton, BorderLayout.EAST);

        // 计算图片面板的高度，使其占据页面高度的 60%
        int imagePanelHeight = (int) (detailDialog.getHeight() * 0.6);
        imagePanel.setPreferredSize(new Dimension(detailDialog.getWidth(), imagePanelHeight));
        detailDialog.add(imagePanel, BorderLayout.NORTH);

        // 图书信息
        JPanel infoPanel = new JPanel();
        infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
        JLabel nameLabel = new JLabel(book.name);
        nameLabel.setFont(new Font("宋体", Font.BOLD, 24));
        JLabel priceLabel = new JLabel(String.format("价格: ¥%.2f", book.price));
        priceLabel.setFont(new Font("宋体", Font.PLAIN, 18));

        nameLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        priceLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

        infoPanel.add(nameLabel);
        infoPanel.add(priceLabel);

        // 操作按钮
        JPanel buttonPanel = new JPanel();
        JButton addToCartButton = new JButton("加入购物车");
        // 增大加入购物车按钮尺寸
        addToCartButton.setPreferredSize(new Dimension(120, 40));
        JButton buyNowButton = new JButton("立即下单");
        addToCartButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 检查购物车中是否已存在该商品
                for (CartItem item : cart) {
                    if (item.book == book) {
                        JOptionPane.showMessageDialog(detailDialog, "该商品已在购物车中");
                        return;
                    }
                }
                cart.add(new CartItem(book));
                JOptionPane.showMessageDialog(detailDialog, "已加入购物车");
                detailDialog.dispose();
            }
        });
        buyNowButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(detailDialog, "立即下单功能暂未实现");
            }
        });
        buttonPanel.add(addToCartButton);
        buttonPanel.add(buyNowButton);

        // 组合面板
        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.add(infoPanel, BorderLayout.WEST);

        JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        southPanel.add(buttonPanel);
        centerPanel.add(southPanel, BorderLayout.SOUTH);

        detailDialog.add(centerPanel, BorderLayout.CENTER);

        detailDialog.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            SecondHandBookApp app = new SecondHandBookApp();
            app.setVisible(true);
        });
    }
}